﻿using System;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace AsptcpClientTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("客户端测试");
            for (int i = 0; i < 10; i++)
            {
                int m = i;
                Task t = Task.Run(async () =>
                {
                    await Start1Async(" 测试发送"+m+" ");
                });
            }
            Console.ReadLine();
            //tcpClient.Close();
            //tcpClient.Dispose();
        }
        static async Task Start1Async(string msg)
        {
            TcpClient tcpClient = new TcpClient();
            await tcpClient.ConnectAsync("127.0.0.1", 1234);
            if (tcpClient.Connected)
            {
                var stream = tcpClient.GetStream();
                Task wTask = Task.Run(async () =>
                {
                    for (int i = 0; i < 10000000; i++)
                    {

                        if (stream.CanWrite)
                        {
                            int m = i;
                            string str = m + msg + DateTime.Now.ToString();
                            byte[] btsr = System.Text.UTF8Encoding.UTF8.GetBytes(m + ":" + str);
                            Console.WriteLine("服务端"+msg+"i:"+m);
                            await stream.WriteAsync(btsr, 0, btsr.Length);
                        }
                        await Task.Delay(1000);
                    }
                    //await Task.Delay(-1);
                });
                Task rTask = Task.Run(async () =>
                {
                    Console.WriteLine("开始接收服务端消息");
                    while (true)
                    {
                        if (stream.CanRead)
                        {
                            byte[] bts = new byte[1024];
                            int realLen = await stream.ReadAsync(bts, 0, bts.Length);
                            string r = System.Text.UTF8Encoding.UTF8.GetString(bts);
                            Console.WriteLine("客户端接收结果：" + r);
                            if (stream.DataAvailable)
                            {
                                Console.WriteLine("消息体大于1024，暂不接收");
                            }
                        }
                        await Task.Delay(10);
                    }
                });
            }
        }
    }
}
